package com.xue.handler;

import com.google.gson.Gson;
import com.xue.bean.DataBean;
import com.xue.service.DataService;
import com.xue.util.HttpURLConnectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: springboot-outbreak
 * @description: 数据处理类
 * @create: 2020-05-27 09:19
 **/
//组件
@Component
public class DataHandler {

    @Autowired
    private DataService dataService;

    public static String url="https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5 ";

    //修饰的方法，在服务器加载Servlet时运行，而且只执行一次
    @PostConstruct
    public void saveData() {
        try {
            List<DataBean> dataBeans = getBean();
            // 先将数据清空  然后存储数据
            dataService.remove(null);
            dataService.saveBatch(dataBeans);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void updateData(){
        saveData();
    }




    public static List<DataBean> getBean() throws Exception{
//        FileReader fr = new FileReader("tmp.txt");
//        char[] cBuf = new char[1024];
//        int cRead = 0;
//        StringBuilder builder = new StringBuilder();
//        while ((cRead = fr.read(cBuf)) > 0){
//            builder.append(new String(cBuf,0,cRead));
//        }
//        fr.close();
////        System.out.println(builder.toString());
//        Gson gson = new Gson();
//        Map map = gson.fromJson(builder.toString(), Map.class);
////        System.out.println(map);

        //实时获取数据
        String respjson = HttpURLConnectionUtil.doGet(url);
        Gson gson = new Gson();
        Map map = gson.fromJson(respjson, Map.class);
        String subStr = (String) map.get("data");
        Map subMap = gson.fromJson(subStr, Map.class);

        ArrayList arrayList = (ArrayList)subMap.get("areaTree");
        Map dataMap = (Map)arrayList.get(0);
        ArrayList childrenList = (ArrayList)dataMap.get("children");

        List<DataBean> result = new ArrayList<>();
        for (int i =0 ;i < childrenList.size();i++){
            Map tmp = (Map) childrenList.get(i);
            String name = (String) tmp.get("name");

            Map totalMap = (Map) tmp.get("total");
            double nowConfirm = (double)totalMap.get("nowConfirm");
            double confirm = (double)totalMap.get("confirm");
            double heal = (double)totalMap.get("heal");
            double dead = (double)totalMap.get("dead");

            DataBean dataBean = new DataBean(name,(int)nowConfirm,(int)confirm,(int)heal,(int)dead);
            result.add(dataBean);
        }
//        System.out.println(result);
        return result;
    }
}
